# -*- coding: UTF-8 -*-
# cython: language_level=3
import execjs  # pip install PyExecJS
import hashlib
import requests
import time
from retry import retry

from db.proxy_db import ProxyDB
from utils.own_tools import fake_ua

with open('chinaz/generatetoken.js', 'r', encoding='utf-8') as f:
    jsstr = f.read()

js = execjs.compile(jsstr)


@retry(tries=3)
def get_icp_chinaz(host: str):
    if host.startswith('www.'):
        host = host.replace('www.', '').strip()

    assert host

    proxy = ProxyDB().get_proxy()
    assert proxy
    proxy = {'http': proxy, 'https': proxy}

    data = '{"keyword":"%s"}' % host

    rd, key = js.call('generateHostKey', data)
    ts = str(int(time.time() * 1000))
    key = rd + key
    rd = rd[:-1]
    token_str = key + "*#|&" + ts
    token = hashlib.md5(token_str.encode(encoding='utf-8')).hexdigest()
    headers = {
        "Accept": "application/json, text/javascript, */*; q=0.01",
        "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
        "Cache-Control": "no-cache",
        "Connection": "keep-alive",
        "Content-Type": "application/json",
        "DNT": "1",
        "Origin": "https://icp.chinaz.com",
        "Pragma": "no-cache",
        "Referer": f"https://icp.chinaz.com",
        "Sec-Fetch-Dest": "empty",
        "Sec-Fetch-Mode": "cors",
        "Sec-Fetch-Site": "same-origin",
        "User-Agent": fake_ua.random,
        "X-Requested-With": "XMLHttpRequest",
        "key": key,
        "rd": rd,
        "sec-ch-ua": "\"Microsoft Edge\";v=\"113\", \"Chromium\";v=\"113\", \"Not-A.Brand\";v=\"24\"",
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": "\"Windows\"",
        "token": token,
        "ts": ts
    }
    api_url = "https://icp.chinaz.com/index/api/queryPermit"
    response = requests.post(api_url, headers=headers, proxies=proxy, data=data.encode(encoding='utf-8'))
    response.raise_for_status()
    response = response.json()
    # print(response)
    assert response['code'] == 0
    return response.get('data', '').get('permit')


if __name__ == '__main__':
    print(get_icp_chinaz('www.baidu.com'))
    print(get_icp_chinaz('naturaled.cnplusrite.com.cn普罗斯.网址'))
